package com.rabbitmq.ChattingRoom.hanlder;

import com.rabbitmq.ChattingRoom.config.RedisUtilTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@Component
@WebFilter(urlPatterns = {"/*"})
public class TokenFilter implements Filter {

    private RedisUtilTemplate redisUtilTemplate = new RedisUtilTemplate();
    private static final String[] NOCHECKURLS = new String[] {
            "/user/login",
            "/user/register"
    };

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        if (!Arrays.asList(NOCHECKURLS).contains(request.getRequestURI())) {
            // 获取请求头 token 参数
            String token = request.getHeader("TOKEN");
            if (StringUtils.isEmpty(token) || StringUtils.isEmpty(redisUtilTemplate.get(token))) {
                request.getRequestDispatcher("/error/token").forward(request,response);
            }else {
                filterChain.doFilter(request,response);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }

}
